﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace LunarSF.SHomeWorkshop.LunarMarkdownEditor.TreeMapCompiler
{
    internal class OrgMapCompiler
    {
        internal static string Run(string treeMapText, ref MarkdownSharp.Markdown md)
        {
            return new OrgNodesManager(treeMapText, ref md).ToHtml();
        }
    }

    internal class OrgNode : TreeNode
    {
        public OrgNode Parent { get; set; }

        public List<OrgNode> Children { get; set; } = null;

        /// <summary>
        /// 同级节点中位于本节点前的所有兄弟节点。
        /// </summary>
        public List<OrgNode> PreNodes
        {
            get
            {
                if (Parent == null || Parent.Children.Count <= 1) return null;

                var list = new List<OrgNode>();

                for (int i = 0; i < Parent.Children.IndexOf(this); i++)
                {
                    list.Add(Parent.Children[i]);
                }

                return list;
            }
        }

        public OrgNode PreNode
        {
            get
            {
                var preNodes = this.PreNodes;
                if (preNodes != null && preNodes.Count > 0)
                {
                    return preNodes[preNodes.Count - 1];
                }

                return null;
            }
        }

        /// <summary>
        /// 同级节点中位于本节点之后的所有节点。
        /// </summary>
        public List<OrgNode> NextNodes
        {
            get
            {
                if (Parent == null || Parent.Children.Count <= 1) return null;

                var list = new List<OrgNode>();
                for (int i = Parent.Children.IndexOf(this) + 1; i < Parent.Children.Count; i++)
                {
                    list.Add(Parent.Children[i]);
                }

                return list;
            }
        }

        public OrgNode NextNode
        {
            get
            {
                if (Parent == null || Parent.Children.Count <= 1) return null;

                var nextNodes = this.NextNodes;
                if (nextNodes != null && nextNodes.Count > 0)
                {
                    return nextNodes[0];
                }

                return null;
            }
        }

        /// <summary>
        /// 所有后代节点。
        /// </summary>
        public List<OrgNode> AllDescendants = null;

        public bool IsRootNode { get { return Level == 1; } }

        /// <summary>
        /// 如果自己就是RootNode，此属性应设置为自身。
        /// </summary>
        public OrgNode RootNode { get; set; }

        public int Size { get; set; }

        public TreeCellLocation Location { get; set; }

        /// <summary>
        /// 只有 RootNode 才有意义。
        /// </summary>
        public int MaxLevel { get; set; }

        /// <summary>
        /// 所有直到 RootNode 的祖先节点。一个节点的坐标由其祖先节点逐次计算而来。
        /// </summary>
        public List<OrgNode> AncestNodes
        {
            get
            {
                var list = new List<OrgNode>();

                var parent = this.Parent;
                while (parent != null && parent.Level > 1)  // 注意：主标题无意义。
                {
                    list.Insert(0, parent);
                    parent = parent.Parent;
                }

                return list;
            }
        }

        public bool HasChild
        {
            get
            {
                return Children != null && Children.Count > 0;
            }
        }

        /// <summary>
        /// 只有 RootNode 应调用此方法。
        /// </summary>
        /// <returns></returns>
        internal string ToHtml()
        {
            if (IsRootNode == false) return "";

            var regex = new Regex(@"[\[【][ 　\t]*?((li?st)|([ 　\t]*?[\<\>]?[ 　\t]*?org))[ 　\t]*?[\]】]", RegexOptions.IgnoreCase);
            string title = Tail;
            string directionMark;
            var matchTitle = regex.Match(Tail);
            if (matchTitle.Success)
            {
                directionMark = matchTitle.Value.Trim(new char[] { '【', '】', '[', ']', ' ', '　', '\t', });
            }
            else
            {
                directionMark = "org";
            }

            title = title.Trim();

            OrgMapDirection direction = OrgMapDirection.Right;  // 默认右向，最先实现！
            if (directionMark.StartsWith("<"))
            {
                direction = OrgMapDirection.Left;
            }
            title = Tail.Substring(matchTitle.Length);

            var cols = MaxLevel * 3 - 2;
            var rows = Size * 4;

            var cells = new TreeCell[rows, cols];

            for (int ri = 0; ri < rows; ri++)
            {
                for (int ci = 0; ci < cols; ci++)
                {
                    cells[ri, ci] = new TreeCell();
                    cells[ri, ci].ColumnOrRowSpan = 1;
                    cells[ri, ci].Type = TreeCellType.Empty;
                }
            }

            if (AllDescendants == null || AllDescendants.Count <= 0) return Tail + " 无下级节点！\r\n";

            var classOrIdRegex = new Regex(@"[(（][ 　\t]*?[&@][ 　\t]*?[a-zA-Z][a-zA-Z0-9\-_]{0,}[ 　\t]*?[)）][ 　\t]*?$");

            var sb = new StringBuilder();
            if (direction == OrgMapDirection.Right)
            {
                sb.Append("<table class='org_map_right'>");
                foreach (var node in AllDescendants)
                {
                    var ancestNodes = node.AncestNodes;                // location 从 1 开始！！！
                    var location = new TreeCellLocation() { CellColumn = (node.Level - 1) * 3 + 1, };
                    foreach (var ancestNode in ancestNodes)
                    {
                        var sizeSum = 0;
                        var preBrothers = ancestNode.PreNodes;
                        if (preBrothers != null)
                        {
                            foreach (var preBrother in preBrothers)
                            {
                                sizeSum += preBrother.Size * 4;
                            }
                        }
                        location.CellRow += sizeSum;
                    }
                    var preNodes = node.PreNodes;
                    if (preNodes != null && preNodes.Count > 0)
                    {
                        var sizeSum = 0;
                        for (int i = 0; i < preNodes.Count; i++)
                        {
                            sizeSum += preNodes[i].Size * 4;
                        }
                        location.CellRow += sizeSum;
                    }
                    location.CellRow += node.Size * 2; // 其实是 * 4 / 2;
                    node.Location = location;
                }

                // 将状态刷新到二维数组中
                cells[rows / 2 - 1, 0].Type = TreeCellType.Title;
                cells[rows / 2 - 1, 0].ColumnOrRowSpan = 2;
                cells[rows / 2 - 1, 0].Node = this;

                cells[rows / 2, 0].Type = TreeCellType.Hided;

                cells[rows / 2 - 1, 1].Type = TreeCellType.Line;  // 右侧横线

                if (this.Children.Count > 1)
                {
                    for (int i = this.Children[0].Location.CellRow; i < this.Children[this.Children.Count - 1].Location.CellRow - 1; i++)
                    {
                        cells[i, 2].Type = TreeCellType.MainLine;
                    }
                    // 不应该在这里加拐角线
                    // cells[this.Children[this.Children.Count - 1].Location.CellRow, 2].Type = TreeCellType.CrossLine;
                }

                foreach (var node in AllDescendants)
                {
                    var rowIndex = node.Location.CellRow - 1;
                    var colIndex = node.Location.CellColumn - 1;

                    cells[rowIndex, colIndex].Node = node;

                    cells[rowIndex, colIndex].Type = TreeCellType.Node;       // 节点单元格
                    cells[rowIndex, colIndex].ColumnOrRowSpan = 2;            // 节点单元格实际占两格，这样才能在左右两侧画横向中线
                    cells[rowIndex + 1, colIndex].Type = TreeCellType.Hided;  // 节点单元格占两格，下面这格就要被隐藏，生成 Html 片段时应忽略。

                    if (node.PreNodes != null && node.PreNodes.Count >= 1)
                    {
                        // 同级最后一个节点
                        cells[rowIndex, colIndex - 1].Type = TreeCellType.CrossLine;   // 左中横线及上级竖线
                    }
                    else
                    {
                        cells[rowIndex, colIndex - 1].Type = TreeCellType.Line;   // 左中横线
                    }

                    if (node.HasChild)
                    {
                        cells[rowIndex, colIndex + 1].Type = TreeCellType.Line;  // 右中横线

                        if (node.Children.Count > 1)
                        {
                            for (int v = node.Children[0].Location.CellRow; v < node.Children[node.Children.Count - 1].Location.CellRow; v++)
                            {
                                cells[v, colIndex + 2].Type = TreeCellType.MainLine;
                            }
                            // 不应在这里加拐角线
                            // cells[node.Children[node.Children.Count - 1].Location.CellRow + 1, colIndex + 2].Type = TreeCellType.CrossLine;
                        }
                    }
                }

                for (var i = 0; i < rows; i++)
                {
                    sb.Append("<tr class='org_map_row'>");
                    for (int j = 0; j < cols; j++)
                    {
                        switch (cells[i, j].Type)
                        {
                            case TreeCellType.MainLine:
                                {
                                    sb.Append("<td class='org_map_left_line'><li class='org_map_left_line'/></td>");
                                    break;
                                }
                            case TreeCellType.Empty:
                                {
                                    sb.Append("<td class='org_map_empty'><li class='org_map_empty'/></td>");
                                    break;
                                }
                            case TreeCellType.Line:
                                {
                                    sb.Append("<td class='org_map_bottom_line'><li class='org_map_bottom_line'/></td>");
                                    break;
                                }
                            case TreeCellType.CrossLine:
                                {
                                    sb.Append("<td class='org_map_cross_left_line'><li class='org_map_cross_left_line'/></td>");
                                    break;
                                }
                            case TreeCellType.Title:
                                {
                                    var tempText = title;
                                    var matchClassOrId = classOrIdRegex.Match(tempText);
                                    if (matchClassOrId.Success)
                                    {
                                        var realTail = tempText.Substring(0, tempText.Length - matchClassOrId.Length);
                                        var mark = matchClassOrId.Value.Trim(new char[] { ' ', '　', '\t', '(', '（', ')', '）', });
                                        if (mark.StartsWith("&"))
                                        {
                                            mark = " " + mark.TrimStart(new char[] { ' ', '　', '\t', '&' });
                                            sb.Append($"<td class='org_map_title org_map_level_1{mark}' rowspan='2'><li class='org_map_title org_map_level_1{mark}'>");
                                            sb.Append(CustomMarkdownSupport.FormatLineContent(ref OrgNodesManager.Md, realTail));
                                        }
                                        else  // if( mark.StartsWith("@")
                                        {
                                            mark = " id='" + mark.TrimStart(new char[] { ' ', '　', '\t', '@' }) + "'";
                                            sb.Append($"<td{mark} class='org_map_title org_map_level_1' rowspan='2'><li{mark} class='org_map_title org_map_level_1'>");
                                            sb.Append(CustomMarkdownSupport.FormatLineContent(ref OrgNodesManager.Md, realTail));
                                        }
                                    }
                                    else
                                    {
                                        sb.Append("<td class='org_map_title org_map_level_1' rowspan='2'><li class='org_map_title org_map_level_1'>");
                                        sb.Append(CustomMarkdownSupport.FormatLineContent(ref OrgNodesManager.Md, title));
                                    }
                                    sb.Append("</li></td>");
                                    break;
                                }
                            case TreeCellType.Node:
                                {
                                    var tempText = cells[i, j].Node.Tail;
                                    var matchClassOrId = classOrIdRegex.Match(tempText);
                                    if (matchClassOrId.Success)
                                    {
                                        var realTail = tempText.Substring(0, tempText.Length - matchClassOrId.Length);
                                        var mark = matchClassOrId.Value.Trim(new char[] { ' ', '　', '\t', '(', '（', ')', '）', });
                                        if (mark.StartsWith("&"))
                                        {
                                            mark = " " + mark.TrimStart(new char[] { ' ', '　', '\t', '&' });
                                            sb.Append($"<td class='org_map_node org_map_level_{cells[i, j].Node.Level}{mark}' rowspan='2'><li class='org_map_node org_map_level_{cells[i, j].Node.Level}{mark}'>");
                                            sb.Append(CustomMarkdownSupport.FormatLineContent(ref OrgNodesManager.Md, realTail));
                                        }
                                        else  // if( mark.StartsWith("@")
                                        {
                                            mark = " id='" + mark.TrimStart(new char[] { ' ', '　', '\t', '@' }) + "'";
                                            sb.Append($"<td{mark} class='org_map_node org_map_level_{cells[i, j].Node.Level}' rowspan='2'><li{mark} class='org_map_node org_map_level_{cells[i, j].Node.Level}'>");
                                            sb.Append(CustomMarkdownSupport.FormatLineContent(ref OrgNodesManager.Md, realTail));
                                        }
                                    }
                                    else
                                    {
                                        sb.Append($"<td class='org_map_node org_map_level_{cells[i, j].Node.Level}' rowspan='2'><li class='org_map_node org_map_level_{cells[i, j].Node.Level}'>");
                                        sb.Append(CustomMarkdownSupport.FormatLineContent(ref OrgNodesManager.Md, tempText));
                                    }
                                    sb.Append("</li></td>");
                                    break;
                                }
                            default: continue;
                        }
                    }
                }
            }
            else  // direction == OrgMapDirection.Left
            {
                sb.Append("<table class='org_map_left'>");

                foreach (var node in AllDescendants)
                {
                    var ancestNodes = node.AncestNodes;                // location 从 1 开始！！！
                    var location = new TreeCellLocation() { CellColumn = cols - ((node.Level - 1) * 3), };
                    foreach (var ancestNode in ancestNodes)
                    {
                        var sizeSum = 0;
                        var preBrothers = ancestNode.PreNodes;
                        if (preBrothers != null)
                        {
                            foreach (var preBrother in preBrothers)
                            {
                                sizeSum += preBrother.Size * 4;
                            }
                        }
                        location.CellRow += sizeSum;
                    }
                    var preNodes = node.PreNodes;
                    if (preNodes != null && preNodes.Count > 0)
                    {
                        var sizeSum = 0;
                        for (int i = 0; i < preNodes.Count; i++)
                        {
                            sizeSum += preNodes[i].Size * 4;
                        }
                        location.CellRow += sizeSum;
                    }
                    location.CellRow += node.Size * 2; // 其实是 * 4 / 2;
                    node.Location = location;
                }

                // 将状态刷新到二维数组中
                cells[rows / 2 - 1, cols - 1].Type = TreeCellType.Title;
                cells[rows / 2 - 1, cols - 1].ColumnOrRowSpan = 2;
                cells[rows / 2 - 1, cols - 1].Node = this;

                cells[rows / 2, cols - 1].Type = TreeCellType.Hided;

                cells[rows / 2 - 1, cols - 2].Type = TreeCellType.Line;  // 左侧横线

                if (this.Children.Count > 1)
                {
                    for (int i = this.Children[0].Location.CellRow; i < this.Children[this.Children.Count - 1].Location.CellRow - 1; i++)
                    {
                        cells[i, cols - 3].Type = TreeCellType.MainLine;
                    }
                    // 不应该在这里加拐角线
                    // cells[this.Children[this.Children.Count - 1].Location.CellRow, 2].Type = TreeCellType.CrossLine;
                }

                foreach (var node in AllDescendants)
                {
                    var rowIndex = node.Location.CellRow - 1;
                    var colIndex = node.Location.CellColumn - 1;

                    cells[rowIndex, colIndex].Node = node;

                    cells[rowIndex, colIndex].Type = TreeCellType.Node;       // 节点单元格
                    cells[rowIndex, colIndex].ColumnOrRowSpan = 2;            // 节点单元格实际占两格，这样才能在左右两侧画横向中线
                    cells[rowIndex + 1, colIndex].Type = TreeCellType.Hided;  // 节点单元格占两格，下面这格就要被隐藏，生成 Html 片段时应忽略。

                    if (node.PreNodes != null && node.PreNodes.Count >= 1)
                    {
                        // 同级最后一个节点
                        cells[rowIndex, colIndex + 1].Type = TreeCellType.CrossLine;   // 右中横线及上级竖线
                    }
                    else
                    {
                        cells[rowIndex, colIndex + 1].Type = TreeCellType.Line;   // 右中横线
                    }

                    if (node.HasChild)
                    {
                        cells[rowIndex, colIndex - 1].Type = TreeCellType.Line;  // 左中横线

                        if (node.Children.Count > 1)
                        {
                            for (int v = node.Children[0].Location.CellRow; v < node.Children[node.Children.Count - 1].Location.CellRow; v++)
                            {
                                cells[v, colIndex - 2].Type = TreeCellType.MainLine;
                            }
                            // 不应在这里加拐角线
                            // cells[node.Children[node.Children.Count - 1].Location.CellRow + 1, colIndex + 2].Type = TreeCellType.CrossLine;
                        }
                    }
                }

                for (var i = 0; i < rows; i++)
                {
                    sb.Append("<tr class='org_map_row'>");
                    for (int j = 0; j < cols; j++)
                    {
                        switch (cells[i, j].Type)
                        {
                            case TreeCellType.MainLine:
                                {
                                    sb.Append("<td class='org_map_right_line'><li class='org_map_right_line'/></td>");
                                    break;
                                }
                            case TreeCellType.Empty:
                                {
                                    sb.Append("<td class='org_map_empty'><li class='org_map_empty'/></td>");
                                    break;
                                }
                            case TreeCellType.Line:
                                {
                                    sb.Append("<td class='org_map_bottom_line'><li class='org_map_bottom_line'/></td>");
                                    break;
                                }
                            case TreeCellType.CrossLine:
                                {
                                    sb.Append("<td class='org_map_cross_right_line'><li class='org_map_cross_right_line'/></td>");
                                    break;
                                }
                            case TreeCellType.Title:
                                {
                                    var tempText = title;
                                    var matchClassOrId = classOrIdRegex.Match(tempText);
                                    if (matchClassOrId.Success)
                                    {
                                        var realTail = tempText.Substring(0, tempText.Length - matchClassOrId.Length);
                                        var mark = matchClassOrId.Value.Trim(new char[] { ' ', '　', '\t', '(', '（', ')', '）', });
                                        if (mark.StartsWith("&"))
                                        {
                                            mark = " " + mark.TrimStart(new char[] { ' ', '　', '\t', '&' });
                                            sb.Append($"<td class='org_map_title org_map_level_1{mark}' rowspan='2'><li class='org_map_title org_map_level_1{mark}'>");
                                            sb.Append(CustomMarkdownSupport.FormatLineContent(ref OrgNodesManager.Md, realTail));
                                        }
                                        else  // if( mark.StartsWith("@")
                                        {
                                            mark = " id='" + mark.TrimStart(new char[] { ' ', '　', '\t', '@' }) + "'";
                                            sb.Append($"<td{mark} class='org_map_title org_map_level_1' rowspan='2'><li{mark} class='org_map_title org_map_level_1'>");
                                            sb.Append(CustomMarkdownSupport.FormatLineContent(ref OrgNodesManager.Md, realTail));
                                        }
                                    }
                                    else
                                    {
                                        sb.Append("<td class='org_map_title org_map_level_1' rowspan='2'><li class='org_map_title org_map_level_1'>");
                                        sb.Append(CustomMarkdownSupport.FormatLineContent(ref OrgNodesManager.Md, title));
                                    }
                                    sb.Append("</li></td>");
                                    break;
                                }
                            case TreeCellType.Node:
                                {
                                    var tempText = cells[i, j].Node.Tail;
                                    var matchClassOrId = classOrIdRegex.Match(tempText);
                                    if (matchClassOrId.Success)
                                    {
                                        var realTail = tempText.Substring(0, tempText.Length - matchClassOrId.Length);
                                        var mark = matchClassOrId.Value.Trim(new char[] { ' ', '　', '\t', '(', '（', ')', '）', });
                                        if (mark.StartsWith("&"))
                                        {
                                            mark = " " + mark.TrimStart(new char[] { ' ', '　', '\t', '&' });
                                            sb.Append($"<td class='org_map_node org_map_level_{cells[i, j].Node.Level}{mark}' rowspan='2'><li class='org_map_node org_map_level_{cells[i, j].Node.Level}{mark}'>");
                                            sb.Append(CustomMarkdownSupport.FormatLineContent(ref OrgNodesManager.Md, realTail));
                                        }
                                        else  // if( mark.StartsWith("@")
                                        {
                                            mark = " id='" + mark.TrimStart(new char[] { ' ', '　', '\t', '@' }) + "'";
                                            sb.Append($"<td{mark} class='org_map_node org_map_level_{cells[i, j].Node.Level}' rowspan='2'><li{mark} class='org_map_node org_map_level_{cells[i, j].Node.Level}'>");
                                            sb.Append(CustomMarkdownSupport.FormatLineContent(ref OrgNodesManager.Md, realTail));
                                        }
                                    }
                                    else
                                    {
                                        sb.Append($"<td class='org_map_node org_map_level_{cells[i, j].Node.Level}' rowspan='2'><li class='org_map_node org_map_level_{cells[i, j].Node.Level}'>");
                                        sb.Append(CustomMarkdownSupport.FormatLineContent(ref OrgNodesManager.Md, tempText));
                                    }
                                    sb.Append("</li></td>");
                                    break;
                                }
                            default: continue;
                        }
                    }
                }
            }
            sb.Append("</table>");
            return sb.ToString();
        }
    }

    /// <summary>
    /// 向上、下并没有开发。这是因为使用 Table 元素来模拟图形，当一个节点只有两个子节点时横向间距过大，极不实用。
    /// </summary>
    public enum OrgMapDirection
    {
        /// <summary>
        /// 向右开口，最先实现。
        /// </summary>
        Right,
        /// <summary>
        /// 向左开口。
        /// </summary>
        Left,
    }

    public class TreeCellLocation
    {
        public int CellRow { get; set; }
        public int CellColumn { get; set; }
    }

    internal class OrgNodesManager
    {
        public static MarkdownSharp.Markdown Md = null;

        internal OrgNodesManager(string treeText, ref MarkdownSharp.Markdown md)
        {
            OrgNodesManager.Md = md;

            if (string.IsNullOrEmpty(treeText)) return;

            var lines = treeText.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            if (lines.Length <= 0) return;

            var preLevel = 0;
            foreach (var line in lines)
            {
                if (CustomMarkdownSupport.IsTreeListTextLine(line, out string header, out string tail, out int level) == false) continue;

                if (preLevel == 1 && level == 1)
                {
                    //添加一个节点，防止崩溃。
                    NodeList.Add(new OrgNode() { Tail = "", Level = 2, });
                }

                var newNode = new OrgNode() { Tail = tail, Level = level };
                NodeList.Add(newNode);

                preLevel = level;
            }

            BuildRelations();

            // 逐层计算每个节点的尺寸
            var rootNodes = new List<OrgNode>();
            foreach (var node in NodeList)
            {
                if (node.Level == 1)
                {
                    rootNodes.Add(node);
                }
            }

            if (rootNodes.Count > 0)
            {
                foreach (var node in rootNodes)
                {
                    node.Size = RefreshSize(node);
                }
            }

            // 输出测试结果
            //var resultText = new StringBuilder();
            //foreach (var node in NodeList)
            //{
            //    resultText.AppendLine(node.Header + node.Tail + $"--Size:{node.Size}");
            //}

            //System.IO.File.WriteAllText("D:\\xxx.txt", resultText.ToString(), Encoding.UTF8);
        }

        internal string ToHtml()
        {
            if (NodeList == null || NodeList.Count <= 0) return "";

            var sb = new StringBuilder();
            foreach (var node in NodeList)
            {
                if (node.IsRootNode)
                    sb.Append(node.ToHtml());
            }

            return sb.ToString();
        }

        /// <summary>
        /// 逐层递归计算节点及其子节点要占多少格。
        /// </summary>
        internal int RefreshSize(OrgNode node)
        {
            if (node.Children == null || node.Children.Count <= 0)
            {
                return 1;
            }

            int size = 1;  // 每个节点都占1格
            foreach (var child in node.Children)
            {
                child.Size = RefreshSize(child);
                size += child.Size;
            }
            if (size > 1)
            {
                return size - 1;
            }

            return size;
        }

        internal List<OrgNode> NodeList = new List<OrgNode>();

        /// <summary>
        /// 理清上下级关系。
        /// </summary>
        internal void BuildRelations()
        {
            if (NodeList.Count <= 0) return;

            for (int i = 0; i < NodeList.Count; i++)
            {
                var curNode = NodeList[i];
                curNode.Children = null;

                var children = new List<OrgNode>();
                for (int j = i + 1; j < NodeList.Count; j++)
                {
                    var node = NodeList[j];
                    if (node.Level <= curNode.Level)
                    {
                        // 同级或上级
                        break;
                    }
                    else if (node.Level == curNode.Level + 1)
                    {
                        // 子级
                        node.Parent = curNode;
                        children.Add(node);
                    }
                    //else continue;
                }

                if (children.Count > 0)
                {
                    curNode.Children = children;
                }
            }

            // 给所有根节点添加上所有子孙节点。
            OrgNode preRootNode = null;
            var maxLevel = 1;
            for (int i = 0; i < NodeList.Count; i++)
            {
                var node = NodeList[i];
                if (node.Level == 1)
                {
                    if (preRootNode != null)
                    {
                        preRootNode.MaxLevel = maxLevel;
                    }
                    preRootNode = node;
                    maxLevel = 1;  // 恢复
                    continue;
                }
                else
                {
                    if (preRootNode != null)
                    {
                        if (preRootNode.AllDescendants == null)
                            preRootNode.AllDescendants = new List<OrgNode>();

                        node.RootNode = preRootNode;
                        preRootNode.AllDescendants.Add(node);
                        maxLevel = Math.Max(maxLevel, node.Level);
                    }
                }
            }

            if (preRootNode != null)
            {
                preRootNode.MaxLevel = maxLevel;
            }

            // 刷新所有节点的 Location

        }
    }
}
